﻿using System;
using System.Windows.Forms;
using CodePlex.DnD4eCampaignManager.CampaignManagerControlLibrary;
using CodePlex.DnD4eCampaignManager.ControlLibrary;
using CodePlex.DnD4eCampaignManager.Presentation;
using CodePlex.DnD4eCampaignManager.Presentation.ViewInterfaces;
using CodePlex.DnD4eCampaignManager.Repositories.Interfaces;
using CodePlex.DnD4eCampaignManager.Services.Interfaces;

namespace CodePlex.DnD4eCampaignManager
{
    public partial class CampaignManager : Form, ICampaignManagerView
    {
        private const string CAMPAIGN_PLANNER_TAB_NAME = "CampaignPlanner_Tab";
        private const string COMBAT_TRACKER_TAB_NAME = "CombatTracker_Tab";

        public CampaignManager()
        {
            InitializeComponent();
            Presenter = new CampaignManagerPresenter(this, ServiceLocator.GetInstance<IPlayerCharacterRepository>(),
                                                     ServiceLocator.GetInstance<IMonsterRepository>(),
                                                     ServiceLocator.GetInstance<ILocationRepository>(),
                                                     ServiceLocator.GetInstance<IDungeonsAndDragonsInsiderMonsterImporter>(),
                                                     ServiceLocator.GetInstance<IDungeonsAndDragonsInsiderPlayerCharacterImporter>());
        }

        public string[] CharacterNames
        {
            get { throw new NotImplementedException(); }
            set
            {
                while ( PlayerCharactersMenu.DropDownItems.Count > 2 )
                {
                    PlayerCharactersMenu.DropDownItems.RemoveAt(2);
                }
                foreach ( string characterName in value )
                {
                    ToolStripMenuItem characterMenuItem = new ToolStripMenuItem(characterName)
                                                              {
                                                                  Name = string.Format("Character_{0}", characterName.Replace(" ", string.Empty)),
                                                                  Tag = string.Format("Character_{0}", characterName)
                                                              };
                    characterMenuItem.Click += MenuItem_Click;
                    PlayerCharactersMenu.DropDownItems.Add(characterMenuItem);
                }
            }
        }

        public string ClickedMenuItemTag { get; private set; }
        public string ClickedMenuItemText { get; private set; }

        public bool CloseButtonVisible
        {
            get { throw new NotImplementedException(); }
            set { CloseTabButton.Visible = value; }
        }

        public string[] LocationNames
        {
            set
            {
                while ( LocationsMenu.DropDownItems.Count > 2 )
                {
                    LocationsMenu.DropDownItems.RemoveAt(2);
                }
                foreach ( string locationName in value )
                {
                    ToolStripMenuItem locationMenuItem = new ToolStripMenuItem(locationName)
                                                             {
                                                                 Name = string.Format("Location_{0}", locationName.Replace(" ", string.Empty)),
                                                                 Tag = string.Format("Location_{0}", locationName)
                                                             };
                    locationMenuItem.Click += MenuItem_Click;
                    LocationsMenu.DropDownItems.Add(locationMenuItem);
                }
            }
        }

        public string[] MonsterNames
        {
            set
            {
                while ( MonstersMenu.DropDownItems.Count > 3 )
                {
                    MonstersMenu.DropDownItems.RemoveAt(3);
                }
                foreach ( string monsterName in value )
                {
                    ToolStripMenuItem monsterMenuItem = new ToolStripMenuItem(monsterName)
                                                            {
                                                                Name = string.Format("Monster_{0}", monsterName.Replace(" ", string.Empty)),
                                                                Tag = string.Format("Monster_{0}", monsterName)
                                                            };
                    monsterMenuItem.Click += MenuItem_Click;
                    MonstersMenu.DropDownItems.Add(monsterMenuItem);
                }
            }
        }

        public string[] PlayerCharacterNames
        {
            set
            {
                while ( PlayerCharactersMenu.DropDownItems.Count > 3 )
                {
                    PlayerCharactersMenu.DropDownItems.RemoveAt(3);
                }
                foreach ( string playerCharacterName in value )
                {
                    ToolStripMenuItem playerCharacterMenuItem = new ToolStripMenuItem(playerCharacterName)
                                                                    {
                                                                        Name =
                                                                            string.Format("PlayerCharacter_{0}",
                                                                                          playerCharacterName.Replace(" ", string.Empty)),
                                                                        Tag = string.Format("PlayerCharacter_{0}", playerCharacterName)
                                                                    };
                    playerCharacterMenuItem.Click += MenuItem_Click;
                    PlayerCharactersMenu.DropDownItems.Add(playerCharacterMenuItem);
                }
            }
        }

        public string SelectedTabName
        {
            get { return MainTabControl.SelectedTab != null ? MainTabControl.SelectedTab.Name : string.Empty; }
        }

        public int TabCount
        {
            get { return MainTabControl.TabPages.Count; }
        }

        private CampaignManagerPresenter Presenter { get; set; }

        public void AddCampaignPlannerTab()
        {
            if ( MainTabControl.TabPages.ContainsKey(CAMPAIGN_PLANNER_TAB_NAME) )
            {
                MainTabControl.SelectedIndex = MainTabControl.TabPages.IndexOfKey(CAMPAIGN_PLANNER_TAB_NAME);
            }
            else
            {
                MainTabControl.TabPages.Add(CAMPAIGN_PLANNER_TAB_NAME, "Campaign Planner");
                MainTabControl.SelectedTab = MainTabControl.TabPages[CAMPAIGN_PLANNER_TAB_NAME];
                CampaignPlanningControl campaignPlanningControl = new CampaignPlanningControl();
                MainTabControl.TabPages[CAMPAIGN_PLANNER_TAB_NAME].Controls.Add(campaignPlanningControl);
                campaignPlanningControl.Dock = DockStyle.Fill;
            }
        }

        public void AddCombatTrackerTab()
        {
            if ( MainTabControl.TabPages.ContainsKey(COMBAT_TRACKER_TAB_NAME) )
            {
                MainTabControl.TabPages[MainTabControl.TabPages.IndexOfKey(COMBAT_TRACKER_TAB_NAME)].Focus();
            }
            else
            {
                MainTabControl.TabPages.Add(COMBAT_TRACKER_TAB_NAME, "Combat Tracker");
                CombatEncounterControl combatEncounterControl = new CombatEncounterControl(ServiceLocator.GetInstance<IPlayerCharacterRepository>(),
                                                                                           ServiceLocator.GetInstance<IMonsterRepository>());
                MainTabControl.TabPages[COMBAT_TRACKER_TAB_NAME].Controls.Add(combatEncounterControl);
                MainTabControl.SelectedTab = MainTabControl.TabPages[COMBAT_TRACKER_TAB_NAME];
                combatEncounterControl.Dock = DockStyle.Fill;
            }
        }

        public void AddLocationEditorTab(string locationName)
        {
            if ( string.IsNullOrEmpty(locationName) )
            {
                locationName = ModalStringPicker.GetString("Create New Location", "Enter the new location name:", string.Empty, 500);
            }
            string tabName = string.Format("Location_{0}_Tab", locationName);
            if ( MainTabControl.TabPages.ContainsKey(tabName) )
            {
                MainTabControl.SelectedIndex = MainTabControl.TabPages.IndexOfKey(tabName);
            }
            else
            {
                MainTabControl.TabPages.Add(tabName, locationName);
                LocationControl locationControl = new LocationControl(locationName, ServiceLocator.GetInstance<ILocationRepository>());
                MainTabControl.TabPages[tabName].Controls.Add(locationControl);
                MainTabControl.SelectedTab = MainTabControl.TabPages[tabName];
                locationControl.Dock = DockStyle.Fill;
            }
        }

        public void AddMonsterEditorTab(string monsterName)
        {
            if ( string.IsNullOrEmpty(monsterName) )
            {
                monsterName = ModalStringPicker.GetString("Create New Monster", "Enter the new monster's name:", string.Empty, 500);
            }
            string tabName = string.Format("Monster_{0}_Tab", monsterName);
            if ( MainTabControl.TabPages.ContainsKey(tabName) )
            {
                MainTabControl.SelectedIndex = MainTabControl.TabPages.IndexOfKey(tabName);
            }
            else
            {
                MainTabControl.TabPages.Add(tabName, monsterName);
                MonsterControl monsterControl = new MonsterControl(monsterName, ServiceLocator.GetInstance<IMonsterRepository>());
                MainTabControl.TabPages[tabName].Controls.Add(monsterControl);
                MainTabControl.SelectedTab = MainTabControl.TabPages[tabName];
                monsterControl.Dock = DockStyle.Fill;
            }
        }

        public void AddPlayerCharacterEditorTab(string playerCharacterName)
        {
            if ( string.IsNullOrEmpty(playerCharacterName) )
            {
                playerCharacterName = ModalStringPicker.GetString("Create New Player Character", "Enter the new player character's name:",
                                                                  string.Empty, 600);
            }
            string tabName = string.Format("PlayerCharacter_{0}_Tab", playerCharacterName);
            if ( MainTabControl.TabPages.ContainsKey(tabName) )
            {
                MainTabControl.SelectedIndex = MainTabControl.TabPages.IndexOfKey(tabName);
            }
            else
            {
                MainTabControl.TabPages.Add(tabName, playerCharacterName);
                MainTabControl.SelectedTab = MainTabControl.TabPages[tabName];
                PlayerCharacterControl playerCharacterControl = new PlayerCharacterControl(playerCharacterName,
                                                                                           ServiceLocator.GetInstance<IPlayerCharacterRepository>());
                MainTabControl.TabPages[tabName].Controls.Add(playerCharacterControl);
                playerCharacterControl.Dock = DockStyle.Fill;
            }
        }


        public void Alert(string message)
        {
            MessageBox.Show(message);
        }

        public string MonsterToImport()
        {
            string monsterName = ModalStringPicker.GetString("Import Monster", "Enter the name or id of the monster you would like to import:",
                                                             string.Empty, 600);

            if ( monsterName.Length == 0 )
            {
                return string.Empty;
            }

            bool isId = true;
            foreach ( char ch in monsterName )
            {
                if ( !Char.IsDigit(ch) )
                {
                    isId = false;
                    break;
                }
            }

            DDIBrowser browser = new DDIBrowser();

            if ( isId )
            {
                int id = Int32.Parse(monsterName);
                browser.NavigateToMonsterId(id);
            }
            else
            {
                browser.SearchForMonster(monsterName);
            }

            if ( browser.ShowDialog() == DialogResult.OK )
            {
                return browser.MonsterHtml;
            }

            return string.Empty; //Didn't import a monster
        }

        public void RemoveTab(string tabName)
        {
            if ( MainTabControl.TabPages.ContainsKey(tabName) )
            {
                MainTabControl.TabPages.RemoveByKey(tabName);
            }
        }

        private void CampaignManager_Load(object sender, EventArgs e)
        {
            Presenter.DisplayMonsters();
            Presenter.DisplayPlayerCharacters();
            Presenter.DisplayLocations();
        }

        private void CloseTabButton_Click(object sender, EventArgs e)
        {
            Presenter.CloseSelectedTab();
        }

        private void MenuItem_Click(object sender, EventArgs e)
        {
            ClickedMenuItemTag = ( (ToolStripMenuItem) sender ).Tag.ToString();
            ClickedMenuItemText = ( (ToolStripMenuItem) sender ).Text;
            Presenter.ProcessMenuItemClick();
        }
    }
}